package fr.insta.reverse.uml.java.projectParser;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

import javax.servlet.ServletContext;

import org.apache.bcel.classfile.ClassParser;
import org.apache.bcel.classfile.JavaClass;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipFile;
import org.apache.commons.fileupload.FileItem;

public class ServiceFile
{

	public File getTempFile(ServletContext _servletContext, FileItem _fileProject)
	{
		if (_fileProject != null && _fileProject.getName().endsWith(".jar"))
		{

			String relativeWebPath = "/temp";
			File tempPath = new File(_servletContext.getRealPath(relativeWebPath));

			try
			{
				File copyFile = new File(tempPath, _fileProject.getName());

				_fileProject.write(copyFile);

				return copyFile;
			}
			catch (Exception e)
			{
				e.printStackTrace();
			}
		}

		return null;
	}

	/**
	 * Convert a File to a ZipFile and delete the old temp file
	 * @param _tempFile the file to convert
	 * @return the zip file
	 */
	public ZipFile getZipFile(File _tempFile)
	{
		try
		{
			if (_tempFile != null)
			{

				ZipFile zipFile = new ZipFile(_tempFile);

				_tempFile.delete();
				return zipFile;
			}
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}

		return null;
	}

	/**
	 * Iterate through the Zip File passed as an argument and retrieve all of the java classes inside
	 * @param _zipFile The Zip File to iterate
	 * @return a list of JavaClass
	 */
	public List<JavaClass> getJavaClasses(ZipFile _zipFile)
	{
		List<JavaClass> javaClasses = new ArrayList<>();

		Enumeration<ZipArchiveEntry> entries = _zipFile.getEntries();

		ZipArchiveEntry archiveEntry;

		//iterate through the zip file to retrieve the inner files
		while (entries.hasMoreElements())
		{
			archiveEntry = entries.nextElement();

			String rawFileName = archiveEntry.getName();

			//if it is java files
			if (rawFileName.endsWith(".class"))
			{
				try
				{
					int lastSlashPosition = rawFileName.lastIndexOf("/");

					//substring the slash to retrieve the filename
					String fileName = rawFileName.substring(lastSlashPosition + 1);

					JavaClass javaClass = new ClassParser(_zipFile.getInputStream(archiveEntry), fileName).parse();

					javaClasses.add(javaClass);
				}
				catch (IOException e)
				{
					e.printStackTrace();
				}
			}
		}

		try
		{
			_zipFile.close();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}

		return javaClasses;
	}
}
